#!/usr/bin/env python3
"""
测试服务器和视频访问
"""
import requests
import time
import subprocess
import sys
import os
from pathlib import Path

# 获取配置（从环境变量或使用默认值）
VIDEO_HOST = os.getenv('VIDEO_HOST', '192.168.210.72')
VIDEO_PORT = os.getenv('VIDEO_PORT', '8000')
BASE_URL = f"http://{VIDEO_HOST}:{VIDEO_PORT}"

def test_server():
    """测试服务器是否正常运行"""
    try:
        print(f"🔍 测试服务器连接: {BASE_URL}")
        response = requests.get(f"{BASE_URL}/api/health", timeout=5)
        print(f"✅ 服务器响应: {response.status_code}")
        return True
    except Exception as e:
        print(f"❌ 服务器连接失败: {e}")
        return False

def test_debug_videos():
    """测试调试接口"""
    try:
        print("🔍 测试视频文件调试接口...")
        response = requests.get(f"{BASE_URL}/debug/videos", timeout=5)
        if response.status_code == 200:
            data = response.json()
            print(f"✅ 调试信息:")
            print(f"   上传目录: {data['uploads_dir']}")
            print(f"   目录存在: {data['exists']}")
            print(f"   视频基础URL: {data['video_base_url']}")
            print(f"   文件数量: {len(data['files'])}")
            for file in data['files']:
                print(f"   - {file['name']} ({file['size']} bytes)")
                print(f"     URL: {file['url']}")
            return data
        else:
            print(f"❌ 调试接口响应错误: {response.status_code}")
            return None
    except Exception as e:
        print(f"❌ 调试接口测试失败: {e}")
        return None

def test_video_access(video_filename):
    """测试视频文件访问"""
    try:
        print(f"🔍 测试视频文件访问: {video_filename}")
        video_url = f"{BASE_URL}/videos/{video_filename}"
        
        # 先测试HEAD请求
        response = requests.head(video_url, timeout=10)
        print(f"   HEAD请求响应: {response.status_code}")
        
        if response.status_code == 200:
            print(f"   Content-Type: {response.headers.get('content-type', 'unknown')}")
            print(f"   Content-Length: {response.headers.get('content-length', 'unknown')}")
            
            # 测试部分内容获取
            response = requests.get(video_url, headers={'Range': 'bytes=0-1023'}, timeout=10)
            print(f"   部分内容请求: {response.status_code}")
            if response.status_code in [200, 206]:
                print(f"✅ 视频文件可以正常访问")
                print(f"   完整URL: {video_url}")
                return True
        
        print(f"❌ 视频文件访问失败: {response.status_code}")
        return False
        
    except Exception as e:
        print(f"❌ 视频文件访问测试失败: {e}")
        return False

def main():
    print("🚀 开始测试视频服务...")
    print(f"📍 使用配置: {BASE_URL}")
    
    # 1. 测试服务器
    if not test_server():
        print("❌ 服务器未运行，请先启动: python start.py")
        return
    
    # 2. 测试调试接口
    debug_data = test_debug_videos()
    if not debug_data:
        return
    
    # 3. 测试视频文件访问
    if debug_data['files']:
        for file_info in debug_data['files']:
            test_video_access(file_info['name'])
    else:
        print("⚠️  没有找到上传的视频文件")
        print(f"   请先通过 {BASE_URL}/test 上传一个视频文件")
    
    print("\n📋 测试完成！")
    print("💡 如果视频访问失败，请检查:")
    print("   1. 服务器是否在正确的IP和端口运行")
    print("   2. uploads目录是否存在且有读取权限")
    print("   3. 防火墙是否阻止了端口访问")
    print(f"   4. 当前配置: VIDEO_HOST={VIDEO_HOST}, VIDEO_PORT={VIDEO_PORT}")

if __name__ == "__main__":
    main()